<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, PropType, nextTick } from 'vue'
import echarts, { ECOption } from './config'

const props = defineProps({
	option: {
		type: Object as PropType<ECOption>,
		required: true
	},
	style: {
		type: Object,
		default: () => ({
			width: '100%',
			height: '400px'
		})
	},
	autoResize: {
		type: Boolean,
		default: true
	}
})

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

// 初始化图表
const initChart = async () => {
	if (!chartRef.value) return

	// 等待下一个DOM更新周期
	await nextTick()

	// 确保容器有尺寸
	if (chartRef.value.offsetHeight === 0 || chartRef.value.offsetWidth === 0) {
		setTimeout(initChart, 100)
		return
	}

	chartInstance = echarts.init(chartRef.value)
	chartInstance.setOption(props.option)
}

// 更新图表
watch(
	() => props.option,
	(newOption) => {
		if (chartInstance) {
			chartInstance.setOption(newOption, true)
			// 强制重绘以确保尺寸正确
			setTimeout(() => {
				chartInstance?.resize()
			}, 0)
		}
	},
	{ deep: true }
)

// 处理窗口大小变化
const handleResize = () => {
	if (chartInstance) {
		chartInstance.resize()
	}
}

onMounted(() => {
	initChart()
	if (props.autoResize) {
		window.addEventListener('resize', handleResize)
	}
})

onUnmounted(() => {
	if (chartInstance) {
		chartInstance.dispose()
	}
	if (props.autoResize) {
		window.removeEventListener('resize', handleResize)
	}
})

// 暴露重绘方法
defineExpose({
	resize: handleResize
})
</script>

<template>
	<div ref="chartRef" :style="style"></div>
</template>
